﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ARR.Entities;
using ARR.DataModel.Repositories;
using DDF.Entity;
using System.Transactions;
using ARR.Services.BizRules;

namespace ARR.Services.Domain
{
    public class UnitsOfMeasureDomain
    {
        public static List<UnitOfMeasureConvertion> GetAll()
        {
            var rows = UnitOfMeasureConvertionsRepository.Select();
            var entities = rows.ConvertAll<UnitOfMeasureConvertion>(r => new UnitOfMeasureConvertion(r));

            entities.ForEach(type => type.ChangeState(EntityState.Original));

            return entities;
        }

        public static List<UnitOfMeasureConvertion> GetBySourceUnit(string sourceUnit)
        {
            var rows = UnitOfMeasureConvertionsRepository.Select(x => x.SourceUnit == sourceUnit);
            var entities = rows.ConvertAll<UnitOfMeasureConvertion>(r => new UnitOfMeasureConvertion(r));

            entities.ForEach(type => type.ChangeState(EntityState.Original));

            return entities;
        }

        public static void Save(List<UnitOfMeasureConvertion> unitsOfMeasure)
        {
            var uomsToSave = unitsOfMeasure.Where(x => x.GetEntityState() == EntityState.Modified || x.GetEntityState() == EntityState.New);

            using (TransactionScope scope = new TransactionScope())
            {
                foreach (var uom in uomsToSave)
                {
                    UnitOfMeasureConvertionBizRules.ValidateSave(uom);

                    if (uom.IsValid)
                    {
                        if (uom.GetEntityState() == EntityState.New)
                        {
                            UnitOfMeasureConvertionsRepository.Insert(uom.GetRow());
                        }
                        else if (uom.GetEntityState() == EntityState.Modified)
                        {
                            UnitOfMeasureConvertionsRepository.Update(uom.GetRow());
                        }
                    }
                    else
                    {
                        throw new ARRException(string.Format("La conversión {0} - {1} es invalida.", uom.SourceUnit, uom.TargetUnit));
                    }
                }

                scope.Complete();
            }
        }
    }
}
